// pages/userhome/address/address.js
var app = getApp();
Page({
  data: {

    choo_modal: "none",
    radioValue: 1,
    checked: true,
    afterSafeList:[],
  },
  onLoad: function (options) {
    var that = this;
    // 页面初始化 options为页面跳转所带来的参数
    //获取手机高度
    this.setData({
      navH: app.globalData.navHeight,
      type: options.type,
      communitygroup: options.communitygroup,
      pintuan: options.pintuan,
      pType: options.pType,
    })
    that.setData({
     
      balance: wx.getStorageSync("balance")
    })
    console.info(options)
    var orderId = options.orderId;
    that.setData({
      orderId: orderId
    })
    that.onShow();
    
  },
  delOrder: function (e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定要取消吗？',
      success: function (sm) {
        if (sm.confirm) {
          // 用户点击了确定 可以调用取消订单的方法了
          wx.request({
            url: app.globalData.url + 'delOrder',
            method: 'GET',
            data: {
              orderId: e.target.dataset.ordid,
              userId: wx.getStorageSync("userId")
            },
            success: function (res) {
              wx.showToast({
                title: "取消成功",
                icon: 'none',
                duration: 1500
              })
              wx.navigateBack({ // 返回首页
                delta: 1,
              })
            }
          });
        }
      }
    });
  }, 
  goLogistice: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index
    wx.navigateTo({
      url: '/pages/logistics/logistics?expressCompanyCode=' + this.data.expressArray[e.currentTarget.dataset.index].expressCompanyCode + '&trackingNumber=' + this.data.expressArray[e.currentTarget.dataset.index].trackingNumber + '&expressCompany=' + this.data.expressArray[e.currentTarget.dataset.index].expressCompany + '&expressInfo=' + that.data.expressArray[index].expressInfo + '&thumbnailimage=' + e.currentTarget.dataset.thumbnailimage
    })

  },
  goLogisticeFromReturn: function(e){
    var that = this;
    var index = e.currentTarget.dataset.index;
    wx.navigateTo({
      url: '/pages/logistics/logistics?expressCompanyCode=' + that.data.afterSafeList[index].expressCompanyCode + '&trackingNumber=' + that.data.afterSafeList[index].trackingNumber + '&expressCompany=' + that.data.afterSafeList[index].expressCompany + '&expressInfo=' + that.data.afterSafeList[index].expressInfo + '&thumbnailimage=' + e.currentTarget.dataset.thumbnailimage
    })
  },
  goPay: function (e) {
    var that = this;

    if (that.data.radioValue == 2) {
      var banlance = true;
    } else {
      var banlance = false;
    }
    
    var orderprice = e.target.dataset.orderprice
    if (banlance == true) {
      wx.request({
        url: app.globalData.url + 'balancePay',
        method: 'GET',
        data: {
          userId: wx.getStorageSync("userId"),
          orderId: that.data.orderId,
        },
        success: function (res) {
          if (res.data.result == 1) {
            wx.showToast({
              title: "支付成功",
              icon: 'none'
            })
            that.modal_n();
            wx.requestSubscribeMessage({
              tmplIds: ['kAJx6NsuymODVzrv40WMb0izAscE7-x0RBAiCXGuVeQ'],
              success(res) {
                console.info(res);
                'https%3a%2f%2ftest.zhijiapp.com%2fWeChatMessageSubscription'
              }
            })
            wx.request({
              url: app.globalData.url + "getOrderDetails",
              header: {
                "content-type": "application/x-www-form-urlencoded"
              },
              data: {
                orderId: that.data.orderId
              },
              method: "POST",
              success: function (res) {
                var data = res.data;
                if (data.result === 1) {
                  that.setData({
                    order: data.data,
                    contactTelephone: data.data.contactTelephone,
                    contactAddress: data.data.contactAddress,
                    contactUsername: data.data.contactUsername,
                    list: data.list,
                    orderNumber: data.data.orderNumber,
                    orderTime: data.data.orderTime,
                    orderNumber: data.data.orderNumber,
                    payFinishTime: data.data.payFinishTime,
                    updateTime: data.data.updateTime,
                    orderTrackingNumber: data.list.orderTrackingNumber,
                    orderProductList: data.data.orderProductList,
                    expressArray: data.data.expressArray,
                    afterSafeList: data.data.afterSafeList,
                    deductPoint: data.data.deductPoint,
                    deductPrice: data.data.deductPrice,
                    orderPrice: data.data.orderPrice,
                  })
                  console.info(data.data.expressArray);
                }
              }
            })
          } else {
            wx.showToast({
              title: res.data.errmsg,
              icon: 'none'
            })
          }
        }
      });
    } else {
      wx.request({
        url: app.globalData.url + 'getOrderWeixinPrepayId',
        data: {
          userId: wx.getStorageSync("userId"),
          orderId: that.data.order.orderId,
          orderNumber: that.data.order.orderNumber,
        },
        method: "POST",
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          var resultData = res.data;
          var hisId = resultData.hisId;
          if (res.data.result != 1 && res.data.result != 9) {
            wx.showToast({
              title: "数据异常，请稍后重试",
              icon: 'none'
            })
            return;
          }
          wx.requestPayment({
            'timeStamp': resultData.timeStamp,
            'nonceStr': resultData.nonceString,
            'package': resultData.packageStr,
            'signType': resultData.signType,
            'paySign': resultData.sign,
            //支付成功
            success: function (res) {
              if ("requestPayment:ok" === res.errMsg) {
                wx.showToast({
                  title: '支付成功',
                  icon: 'success',
                  duration: 2000,
                  success: function () {

                    if (that.data.type == 2 && that.data.typeShow != 0) {
                      wx.navigateTo({
                        url: '/pages/assembleDetail/assembleDetail?orderId=' + that.data.orderId + '&back=1'
                      })
                    } else if (that.data.type == 2 && that.data.typeShow == 0) {
                      wx.navigateTo({
                        url: '/pages/paySeccess/paySeccess?orderId=' + that.data.orderId + '&back=1'
                      })
                    } else {
                      console.info(that.data.lipinka);
                      if (that.data.lipinka != 3) {
                        wx.navigateTo({
                          url: '/pages/paySeccess/paySeccess?orderId=' + that.data.orderId + '&back=1'
                        })
                      } else {
                        wx.navigateTo({
                          url: '/pages/giftCardBuySuccess/giftCardBuySuccess?orderId=' + that.data.orderId + '&back=1'
                        })
                      }

                    }

                  }
                })
              }
            },
            //支付或者取消失败
            fail: function (res) {
              if ("requestPayment:fail cancel" === res.errMsg) {
                wx.showToast({
                  title: '取消支付',
                  icon: 'none',
                  duration: 2000,
                  success: function () {
                    if (that.data.type == 2) {
                      wx.navigateBack({
                      });
                      wx.request({
                        url: app.globalData.url + 'delOrder',
                        method: 'GET',
                        data: {
                          orderId: that.data.orderId,
                          userId: wx.getStorageSync("userId")
                        },
                        success: function (res) {
                          wx.navigateBack({ // 返回首页
                            delta: 1,
                          })
                        }
                      });
                    } else {
                      wx.showToast({
                        title: "取消支付",
                        icon: 'none'
                      })
                      wx.navigateBack({
                        delta: 1,
                      });
                      // setTimeout(function () {
                      //   wx.navigateBack({
                      //     delta: 1,
                      //   });
                      // }, 2000) //延迟时间
                    }

                  }
                })
              } else {

                wx.showToast({
                  title: "支付失败",
                  icon: 'none'
                })
              }
            },
          })
        }
      })
    }
  },
  trueGet: function (e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '是否已经收到货物',
      success: function (sm) {
        if (sm.confirm) {
          wx.request({
            url: app.globalData.url + 'orderSigned',
            method: 'GET',
            data: {
              orderId: e.target.dataset.ordid,
              userId: wx.getStorageSync("userId"),
              orderProductId: e.currentTarget.dataset.opid
            },
            success: function (res) {
              wx.request({
                url: app.globalData.url + "getOrderDetails",
                  header: {
                  "content-type": "application/x-www-form-urlencoded"
                },
                data: {
                  orderId: e.target.dataset.ordid
                },
                method: "POST",
                  success: function (res) {
                    var data = res.data;
                    var orderProductList = data.data.orderProductList;
                    if (data.result === 1) {
                      if (data.data.orderStatus == 7000) {
                        that.countTime();
                      }
                      if (data.data.orderStatus == 7010) {
                        wx.request({
                          url: app.globalData.url + 'getParaById',
                          header: {
                            "content-type": "application/x-www-form-urlencoded"
                          },
                          data: {
                            paraId: 'order_product_refund_ audit',
                          },
                          method: "POST",
                          success: function (res) {
                            that.setData({
                              addDayCount: res.data.data.value
                            })
                            var date = new Date();
                            var now = date.getTime();
                            //console.info(a);
                            var edTime = that.getDateStr(null, res.data.data.value);
                            that.setData({
                              edTime: edTime
                            })
                            that.countTime(edTime);
                          }
                        })
                      }
                      orderProductList.forEach((item) => {
                        if (item.product.bookingConsignmentTime != undefined && item.product.bookingEndTime != undefined) {
                          item.product.bookingConsignmentTime = item.product.bookingConsignmentTime.substring(0, 10); //要截取时间的字符串
                          item.product.bookingEndTime = item.product.bookingEndTime.substring(0, 10); //要截取时间的字符串
                        }
                      })
                      console.info(orderProductList);
                      that.setData({
                        order: data.data,
                        orderStatus: data.data.orderStatus,
                        contactTelephone: data.data.contactTelephone,
                        contactAddress: data.data.contactAddress,
                        contactUsername: data.data.contactUsername,
                        list: data.list,
                        orderNumber: data.data.orderNumber,
                        orderTime: data.data.orderTime,
                        orderNumber: data.data.orderNumber,
                        payFinishTime: data.data.payFinishTime,
                        updateTime: data.data.updateTime,
                        orderTrackingNumber: data.list.orderTrackingNumber,
                        orderProductList: data.data.orderProductList,
                        expressArray: data.data.expressArray,
                        deductPoint: data.data.deductPoint,
                        deductPrice: data.data.deductPrice,
                        //afterSafeList: data.data.afterSafeList,
                      })
                    }
                  }
              });
              // wx.navigateTo({
              //   url: '/pages/myOrder/myOrder?type=3'
              // })
            }
          });
        }
      }
    });

  },
  goOut: function (e) {
    var that = this;
    wx.navigateTo({
      url: '/pages/refundDispose/refundDispose?orderId=' + that.data.orderId + '&productId=' + e.currentTarget.dataset.productid + '&opasid=' + e.currentTarget.dataset.opasid + '&opId=' + e.currentTarget.dataset.opid,
    })
    // wx.request({
    //   url: app.globalData.url + 'getWareHouseByProduct',
    //   method: 'GET',
    //   data: {
    //     productId: e.currentTarget.dataset.productid,
    //   },
    //   success: function (res) {
    //     wx.showModal({
    //       title: '退换货地址',
    //       content: '联系人：' + res.data.data.linker + "\r\n电话：" + res.data.data.telephone +"\r\n地址："+res.data.data.address,
    //       success: function (res) {
    //         if (res.confirm) {
    //         } else {
    //         }
    //       }
    //     })
    //   }
    // });

  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    var that = this;
    wx.request({
      url: app.globalData.url + "getOrderDetails",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        orderId: that.data.orderId
      },
      method: "POST",
      success: function (res) {
        var data = res.data;
        var orderProductList = data.data.orderProductList;
        if (data.result === 1) {
          if (data.data.orderStatus == 7000) {
            wx.request({
              url: app.globalData.url + 'getParaById',
              header: {
                "content-type": "application/x-www-form-urlencoded"
              },
              data: {
                paraId: 'not_paid_cancel_time',
              },
              method: "POST",
              success: function (res) {
                that.setData({
                  addDayCount: res.data.data.value
                })
                var date = new Date();
                var now = date.getTime();
                console.info(res.data.data.value);
                var edTime = that.getDateStr(that.data.orderTime, res.data.data.value);
                console.info(edTime);
                that.setData({
                  edTime: edTime
                })
                that.countTime(edTime);
              }
            })
          }
          if (data.data.orderStatus == 7010) {
            wx.request({
              url: app.globalData.url + 'getParaById',
              header: {
                "content-type": "application/x-www-form-urlencoded"
              },
              data: {
                paraId: 'order_product_refund_ audit',
              },
              method: "POST",
              success: function (res) {
                that.setData({
                  addDayCount: res.data.data.value
                })
                var date = new Date();
                var now = date.getTime();
                //console.info(a);
                var edTime = that.getDateStr(null, res.data.data.value);
                that.setData({
                  edTime: edTime
                })
                that.countTime(edTime);
              }
            })
          }
          orderProductList.forEach((item) => {
            if (item.product.bookingConsignmentTime != undefined && item.product.bookingEndTime != undefined) {
              item.product.bookingConsignmentTime = item.product.bookingConsignmentTime.substring(0, 10); //要截取时间的字符串
              item.product.bookingEndTime = item.product.bookingEndTime.substring(0, 10); //要截取时间的字符串
            }
          })
          console.info(orderProductList);
          that.setData({
            order: data.data,
            orderStatus: data.data.orderStatus,
            contactTelephone: data.data.contactTelephone,
            contactAddress: data.data.contactAddress,
            contactUsername: data.data.contactUsername,
            list: data.list,
            orderNumber: data.data.orderNumber,
            orderTime: data.data.orderTime,
            orderNumber: data.data.orderNumber,
            payFinishTime: data.data.payFinishTime,
            updateTime: data.data.updateTime,
            orderTrackingNumber: data.list.orderTrackingNumber,
            orderProductList: data.data.orderProductList,
            expressArray: data.data.expressArray,
            afterSafeList: data.data.afterSafeList,
            communityHeadName: data.data.communityHeadName,
            communityAddress: data.data.communityAddress,
            deductPoint: data.data.deductPoint,
            deductPrice: data.data.deductPrice,
            communityTelephone: data.data.communityTelephone,
            communityDetailAddress: data.data.communityDetailAddress,
          })
        }
      }
    });
    wx.request({
      url: app.globalData.url + 'getProductUserLikeList',
      data: {
        userId: wx.getStorageSync("userId"),
      },
      method: "POST",
      success: function (res) {
        that.setData({
          likeList: res.data.data
        })
       
      }
    })
  },
  goRefund: function (e) {
    if (e.currentTarget.dataset.canrefund == true){
    if (e.currentTarget.dataset.usedtime == undefined) {
      wx.navigateTo({
        url: '/pages/afterSaleCente/afterSaleCente?orderProductId=' + e.currentTarget.dataset.orderpoid + '&orderid=' + e.currentTarget.dataset.orderid + '&status=' + e.currentTarget.dataset.status + '&orderStatus=' + e.currentTarget.dataset.orderStatus + "&refundprice=" + e.currentTarget.dataset.refundprice + '&refund=' + e.currentTarget.dataset.refund + '&exchange=' + e.currentTarget.dataset.exchange + "&buyprice=" + e.currentTarget.dataset.buyprice
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '您的礼品卡已使用无法售后',
        showCancel:false,
        success: function (sm) {
          
        }
      });
    }
    }else{
      wx.showModal({
        title: '提示',
        content: '该商品不支持售后',
        showCancel: false,
        success: function (sm) {

        }
      });
    }
    
  },
  onUnload: function () {
    // 页面关闭
  },
  /**
   * 跳转到产品详情
   */
  toProduct: function (res) {
    var productid = res.currentTarget.dataset.productid;
    var yushou = res.currentTarget.dataset.yushou;
    var consignmenttimestr = res.currentTarget.dataset.consignmenttimestr;
    var endtimestr = res.currentTarget.dataset.endtimestr;
    console.info(yushou);
    if (yushou==0) {
      yushou=undefined
    }
    // wx.navigateTo({
    //   url: '/pages/productDetail/productDetail?productid=' + productid + '&yushou=' + yushou + '&consignmenttimestr=' + consignmenttimestr + '&endtimestr=' + endtimestr,
    // })

  },

  // 弹出
  modal_s: function (e) {
    this.setData({
      choo_modal: "block",
      z: true,
      ordId: e.target.dataset.ordid,
      dis_n:"none"
    });
  },
  //消失
  modal_n: function () {
    this.setData({
      choo_modal: "none",
      z: false,
      dis_n: "block"
    });
  },
  radio: function (e) {
    var that = this;
    var radioValue = e.currentTarget.dataset.value;
    that.setData({
      radioValue: radioValue
    })
    console.info(radioValue);
    if (radioValue == 1) {
      that.setData({
        checked1: false,
        checked: true,
        ordid: e.currentTarget.dataset.ordid
      })
    }
    if (radioValue == 2) {
      that.setData({
        checked1: true,
        checked: false,
        ordid: e.currentTarget.dataset.ordid
      })
    }
  },
  navBack: function () {
    var that = this;
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];   //上一页
    if (that.data.communitygroup==1){
      var pType = 1
    }else{
      var pType = 0
    }
    prevPage.setData({
      pType: pType
    })
    wx.navigateBack({

    })
  },
  countTime:function(edTime) {
    //var edTime ='2020-02-21 22:33:27';
    var that = this;
    var date = new Date();
    var now = date.getTime();
    var endDate = new Date(that.data.edTime.replace(/\.|\-/g, '/'));//设置截止时间
    var end = endDate.getTime();
    var leftTime = end - now; //时间差                              
    var d, h, m, s, ms;
    if (leftTime >= 0) {
      d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
      h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
      m = Math.floor(leftTime / 1000 / 60 % 60);
      s = Math.floor(leftTime / 1000 % 60);
      ms = Math.floor(leftTime % 1000);
      ms = ms < 100 ? "0" + ms : ms
      s = s < 10 ? "0" + s : s
      m = m < 10 ? "0" + m : m
      h = h < 10 ? "0" + h : h
      that.setData({
        countdown: d + "天" + h + "时" + m + "分" + s + "秒",
      })
      //递归每秒调用countTime方法，显示动态时间效果
      setTimeout(that.countTime, 100);
    } else {
      console.log('已截止')
      that.setData({
        countdown: '00:00:00'
      })
    }

  },
  goEvaluation: function (e) {
    wx.navigateTo({
      url: '/pages/userEvaluation/userEvaluation?productid=' + e.currentTarget.dataset.id + '&opid=' + e.currentTarget.dataset.opid
    })
  },
  //获取几天后的日期
  getDateStr:function (today, addDayCount) {
    console.info(addDayCount);
    var dd;
    if(today) {
      dd = new Date(today);
    }else{
      dd = new Date();
    }
    dd.setDate(parseInt(dd.getDate()) + parseInt(addDayCount));//获取AddDayCount天后的日期 
    var y = dd.getFullYear();
    var month = dd.getMonth() + 1;//获取当前月份的日期 
    var d = dd.getDate();
    var h = dd.getHours();
    var m = dd.getMinutes();
    var s = dd.getSeconds();
    if(m < 10) {
      m = '0' + m;
    };
    if(d < 10) {
      d = '0' + d;
    };
    return y + "-" + month + "-" + d + " " + h + ':' + m + ':' + s;
  },
  goExpressList: function (e) {
    wx.navigateTo({
      url: '/pages/expressList/expressList?orderId=' + e.currentTarget.dataset.ordid + "&type=" + e.currentTarget.dataset.type
    })
  },
  goOnlyRefund:function(e){
      wx.navigateTo({
        url: '/pages/refundToFillOut/refundToFillOut?type=' + 3 + '&orderProductId=' + e.currentTarget.dataset.orderpoid + '&productId=' + e.currentTarget.dataset.productid + '&orderid=' + e.currentTarget.dataset.orderid+'&daidahuo=1'
      })
  },
  details: function (res) {
    var productid = res.currentTarget.dataset.productid;
    var type = res.currentTarget.dataset.type;
    wx.navigateTo({
      url: '/pages/productDetail/productDetail?productid=' + productid + '&type=' + type,
    })

  },
})